package com.bestcem.xm.om.service.impl;

import cn.hutool.core.lang.ObjectId;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.enums.ReqErrorCodeEnum;
import com.bestcem.xm.common.core.enums.ResourceErrorCodeEnum;
import com.bestcem.xm.om.constant.NoticeEmailConstant;
import com.bestcem.xm.om.dao.OmIndustryDao;
import com.bestcem.xm.om.dao.PlatformDao;
import com.bestcem.xm.om.entity.OmIndustry;
import com.bestcem.xm.om.entity.OmPlatform;
import com.bestcem.xm.om.enums.*;
import com.bestcem.xm.om.grpc.client.OmOrgGrpcService;
import com.bestcem.xm.om.grpc.service.converter.IndustryConverter;
import com.bestcem.xm.om.grpc.v1.services.GetIndustryContactResponse;
import com.bestcem.xm.om.grpc.v1.services.Industry;
import com.bestcem.xm.om.grpc.v1.services.IndustryInfo;
import com.bestcem.xm.om.service.OmIndustryService;
import com.bestcem.xm.om.service.dto.SampleCodeDTO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * OmIndustryServiceImpl
 *
 * @author zhangfeng <feng.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2021/11/16 16:24
 */
@Service
public class OmIndustryServiceImpl implements OmIndustryService {
    @Resource
    private OmIndustryDao omIndustryDao;
    @Resource
    private PlatformDao platformDao;
    @Resource
    private OmOrgGrpcService omOrgGrpcService;
    @Value("${spring.profiles.active:test}")
    private String appEnv;

    private static final String PROD = "prod";

    private static final Set<String> NORTH_CITY = new HashSet<>();
    private static final Set<String> EAST_CITY = new HashSet<>();
    private static final Set<String> SOUTH_CITY = new HashSet<>();
    private static final Set<String> EXT_EMAIL_LIST = new HashSet<>();

    static {
        NORTH_CITY.add("黑龙江");
        NORTH_CITY.add("吉林");
        NORTH_CITY.add("辽宁");
        NORTH_CITY.add("北京");
        NORTH_CITY.add("天津");
        NORTH_CITY.add("河北");
        NORTH_CITY.add("山西");
        NORTH_CITY.add("内蒙古");
        NORTH_CITY.add("陕西");
        NORTH_CITY.add("甘肃");
        NORTH_CITY.add("青海");
        NORTH_CITY.add("宁夏");
        NORTH_CITY.add("新疆");
        NORTH_CITY.add("西藏");

        EAST_CITY.add("江苏");
        EAST_CITY.add("浙江");
        EAST_CITY.add("上海");
        EAST_CITY.add("安徽");
        EAST_CITY.add("山东");
        EAST_CITY.add("湖北");
        EAST_CITY.add("江西");

        SOUTH_CITY.add("广东");
        SOUTH_CITY.add("广西");
        SOUTH_CITY.add("福建");
        SOUTH_CITY.add("云南");
        SOUTH_CITY.add("贵州");
        SOUTH_CITY.add("四川");
        SOUTH_CITY.add("重庆");
        SOUTH_CITY.add("湖南");
        SOUTH_CITY.add("海南");
        SOUTH_CITY.add("深圳");
        SOUTH_CITY.add("香港");
        SOUTH_CITY.add("台湾");
        SOUTH_CITY.add("澳门");

        EXT_EMAIL_LIST.add(NoticeEmailConstant.XB_EMAIL);
        EXT_EMAIL_LIST.add(NoticeEmailConstant.DAVIS_EMAIL);
        EXT_EMAIL_LIST.add(NoticeEmailConstant.GXM_EMAIL);
    }

    @Override
    public ServiceResult<String> insert(OmIndustry omIndustry) {
        return ServiceResult.success(omIndustryDao.insert(omIndustry));
    }

    @Override
    public ServiceResult<Industry> findById(String id) {
        if (!ObjectId.isValid(id)) {
            return ServiceResult.failWithCode(ReqErrorCodeEnum.PARAM_FORMAT, "id格式应该是ObjectId格式");
        }
        OmIndustry omIndustry = omIndustryDao.findById(id);
        if (Objects.isNull(omIndustry)) {
            return ServiceResult.failWithCode(ResourceErrorCodeEnum.NO_DATA);
        }
        return ServiceResult.success(IndustryConverter.entityToDto(omIndustry));
    }

    @Override
    public ServiceResult<String> updateById(OmIndustry industry) {
        if (!ObjectId.isValid(industry.getId())) {
            return ServiceResult.failWithCode(ReqErrorCodeEnum.PARAM_FORMAT, "id格式应该是ObjectId格式");
        }
        OmIndustry omIndustry = omIndustryDao.findById(industry.getId());
        if (Objects.isNull(omIndustry)) {
            return ServiceResult.failWithCode(ResourceErrorCodeEnum.NO_DATA);
        }
        omIndustryDao.updateById(industry);
        return ServiceResult.success(industry.getId());
    }

    @Override
    public ServiceResult<Integer> deleteById(String id) {
        int i = omIndustryDao.deleteById(id);
        return ServiceResult.success(i);
    }

    @Override
    public ServiceResult<List<Industry>> selectByIds(List<String> ids) {
        List<Industry> list = new ArrayList<>();
        for (String id : ids) {
            OmIndustry omIndustry = omIndustryDao.findById(id);
            if (Objects.nonNull(omIndustry)) {
                list.add(IndustryConverter.entityToDto(omIndustry));
            }
        }
        return ServiceResult.success(list);
    }

    @Override
    public ServiceResult<GetIndustryContactResponse> findByDistrictAndIdOrCode(String district, String id, Integer code) {
        Integer industryCode = 0;
        OmIndustry omIndustry = new OmIndustry();
        if (StringUtils.isNotBlank(id)) {
            omIndustry = omIndustryDao.findById(id);
            if (Objects.isNull(omIndustry)) {
                return ServiceResult.failWithCode(ResourceErrorCodeEnum.NO_DATA);
            }
            industryCode = omIndustry.getCode();
        } else if (Objects.nonNull(code)) {
            omIndustry = omIndustryDao.findByCode(code);
            industryCode = code;
        }
        GetIndustryContactResponse.Builder builder = GetIndustryContactResponse.newBuilder();
        Industry industry = IndustryConverter.entityToDto(omIndustry);
        if (Objects.nonNull(industry)) {
            builder.setIndustry(industry);
        }
        if (StringUtils.isNotEmpty(district)) {
            CEMIndustryCodeEnum cemIndustryCodeEnum = CEMIndustryCodeEnum.getByIndex(industryCode);
            MobileEnum mobileEnum = CodeMobileEnum.getByCemIndustryCodeEnum(cemIndustryCodeEnum);
            MailEnum mailEnum = CodeMailEnum.getByCemIndustryCodeEnum(cemIndustryCodeEnum);

            if (Objects.isNull(mobileEnum)) {
                builder.addPhones(MobileEnum.RETAIL_MOBILE_DICT.getNorthMobile().get(0));
            }

            if (Objects.nonNull(mobileEnum) && Objects.nonNull(mailEnum)) {
                List<String> mobileList;
                List<String> mailList;
                if (StringUtils.equalsAny(district, "North", "north")) {
                    mobileList = mobileEnum.getNorthMobile();
                    mailList = mailEnum.getNorthMail();
                } else if (StringUtils.equalsAny(district, "East", "east")) {
                    mobileList = mobileEnum.getEastMobile();
                    mailList = mailEnum.getEastMail();
                } else if (StringUtils.equalsAny(district, "South", "south")) {
                    mobileList = mobileEnum.getSouthMobile();
                    mailList = mailEnum.getSouthMail();
                } else {
                    return ServiceResult.failWithCode(ReqErrorCodeEnum.PARAM_FORMAT, "未知区域");
                }
                builder.addAllPhones(mobileList);
                builder.addAllEmails(mailList);
            }
        } else {
            // 区域为空，说明是获取销售邮箱，返回客服邮箱 apps_mysql.user.util.utils.get_sales_emails_by_district
            // 测试
            if (PROD.equals(appEnv)) {
                builder.addEmails(NoticeEmailConstant.KF_EMAIL);
                builder.addAllEmails(NoticeEmailConstant.EXT_EMAIL_LIST);
            } else {
                builder.addAllEmails(NoticeEmailConstant.TEST_EMAIL_LIST);
            }
        }
        if (CollectionUtils.isEmpty(builder.getEmailsList())) {
            builder.setDefaultEmail(MailEnum.OTHER_MAIL_DICT.getEastMail().get(0));
        } else {
            builder.setDefaultEmail(builder.getEmails(0));
        }
        return ServiceResult.success(builder.build());
    }

    @Override
    public ServiceResult<IndustryInfo> findByCodeOrRouteOrIp(Integer industryCode, String industryRoute, String ip) {
        OmIndustry omIndustry;
        if (Objects.nonNull(industryCode)) {
            omIndustry = omIndustryDao.findByCode(industryCode);
            if (Objects.isNull(omIndustry)) {
                OmIndustry otherIndustry = omIndustryDao.findByCode(CEMIndustryCodeEnum.APPLICANT_TRADE_OTHER.getIndex());
                if (Objects.isNull(otherIndustry)) {
                    return ServiceResult.failWithCode(ResourceErrorCodeEnum.NOT_FOUND, "没有通用行业，请联系管理员初始化");
                }
                return ServiceResult.failWithCode(ResourceErrorCodeEnum.NOT_FOUND);
            }
        } else if (StringUtils.isNotBlank(industryRoute)) {
            String upperCase = industryRoute.toUpperCase();
            RouteEnum routeEnum = RouteEnum.getByIndex(upperCase);
            if (Objects.isNull(routeEnum)) {
                return ServiceResult.failWithCode(ResourceErrorCodeEnum.NOT_FOUND, "页面没有对应行业");
            }
            omIndustry = omIndustryDao.findByCode(routeEnum.getCemIndustryCodeEnum().getIndex());
            if (Objects.isNull(omIndustry)) {
                return ServiceResult.failWithCode(ResourceErrorCodeEnum.NOT_FOUND, "页面没有对应行业");
            }
        } else {
            return ServiceResult.failWithCode(ResourceErrorCodeEnum.NOT_FOUND, "没有指定行业");
        }

        IndustryInfo.Builder builder = IndustryInfo.newBuilder();
        builder.setId(omIndustry.getId());
        // 统一发送到客服邮箱
        builder.addEmails(NoticeEmailConstant.KF_EMAIL);
        builder.addAllEmails(NoticeEmailConstant.EXT_EMAIL_LIST);
        builder.setName(omIndustry.getName());
        builder.setCode(omIndustry.getCode());
        return ServiceResult.success(builder.build());
    }

    @Override
    public ServiceResult<List<Industry>> listIndustries(String id, Integer code, String name, Integer order) {
        List<OmIndustry> industries = omIndustryDao.listByParam(id, code, name, order);
        // 获取所有行业code
        // 根据Python查询行业处理逻辑(apps_mysql.user.user_utils.get_industry_list),过滤行业信息,排除行业列表中的满意度频道(code=21)和版本定价(code=25)
        List<Integer> industryCodeList = OpenPlantFormBookingIndustryEnum.getIndustryCodeList();
        return ServiceResult.success(industries.stream().filter(industry ->
                OpenPlantFormBookingIndustryEnum.APPLICANT_TRADE_SATISFACTION.getIndex() != industry.getCode()
                        && OpenPlantFormBookingIndustryEnum.APPLICANT_TRADE_VERSION.getIndex() != industry.getCode()
                        && industryCodeList.contains(industry.getCode())).map(IndustryConverter::entityToDto).collect(Collectors.toList()));
    }

    @Override
    public ServiceResult<List<SampleCodeDTO>> listIndustrySampleCode() {
        List<OmPlatform> platformList = platformDao.listByStatus(PlatformStatusEnum.ACTIVED);
        Set<String> codeSet = platformList.stream().map(OmPlatform::getSampleCode)
                .filter(StringUtils::isNotBlank).collect(Collectors.toSet());

        List<SampleCodeDTO> sampleCodeList = omOrgGrpcService.listIndustrySampleCodes(codeSet);
        if (Objects.isNull(sampleCodeList)) {
            return ServiceResult.failWithCode(ResourceErrorCodeEnum.NOT_FOUND, "调用user接口失败");
        }
        return ServiceResult.success(sampleCodeList);
    }
}
